package com.woniuxy.b_realm;

import com.alibaba.druid.sql.visitor.functions.If;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.swing.*;

/**
 * @author lg
 * @time 2020/07/04 11:33:19
 *  我门自定义的Realm必须继承AuthorizingRealm
 */
public class MyRealm extends AuthorizingRealm {
    // 授权
    @Override
     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取身份信息
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal ();
        System.out.println ("授权"+primaryPrincipal);

        SimpleAuthorizationInfo sa=new SimpleAuthorizationInfo ();

         if("abc".equals (primaryPrincipal)){
               sa.addStringPermission ("user:save");
               sa.addStringPermission ("user:find");
          }
         if("xyz".equals (primaryPrincipal)){
                   sa.addStringPermission ("user:delete");
                   sa.addStringPermission ("user:update");
         }

        return sa;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Object principal = token.getPrincipal (); //获取登录人的账号 密码
        String credentials = new String ((char[]) token.getCredentials ()); // 获取 认证是否成功
        if (!"abc".equals (principal) && !"xyz".equals (principal)) {
            return null;

        } else {
            // 认证成功 ，就要给上层返回当前主体的身份。
            // 因为将来进行授权的时候，就要使用身份授权
            String pass = "";
            if ("abc".equals (principal)) {
                pass = "111";
            } else if ("xyz".equals (principal)) {
                pass = "222";
            }
                 //来进行授权的时候，就要使用身份授权
            return new SimpleAuthenticationInfo (principal,pass,"myReleam");
        }

    }
}
